import axios from "axios";
import env from "./env"; 
import router from '@/router'

const service = axios.create({
	baseURL: env.dev.baseUrl, //请求地址
    headers:{
        'Content-Type': 'application/json;charset=UTF-8',
    },
    timeout: 1000 * 180,
    // withCredentials: true
});
// 请求拦截器
service.interceptors.request.use(
    config => {
        if (sessionStorage.getItem('token')) {
        config.headers.token = sessionStorage.getItem('token')
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
 
// 响应拦截器
service.interceptors.response.use(
response => {
    if (response.status && response.status === 200) {
      if (response.data.code === 0) {
        return response.data
      } else if (response.data.code === 401) { 
        this.$message.error("登录已过期，请重新登录！");
        sessionStorage.removeItem("token")
        router.push({ 
          path: '/login'
        })
      }
      return Promise.resolve(response.data)
    }
},
error => {
    return Promise.reject(error);
}
);
export default service;
